package com.martin.dms.web.services.impl;

import java.util.ArrayList;
import java.util.List;

import com.martin.dms.model.Category;
import com.martin.dms.model.Item;
import com.martin.dms.services.CategoryService;
import com.martin.dms.services.ItemService;
import com.martin.dms.web.beans.CategoryBean;
import com.martin.dms.web.beans.ItemBean;
import com.martin.dms.web.services.CategoryFlowService;

/**
 * Implementation of the CategoryFlowService.
 * 
 * @author mtsvetkov
 */
public class CategoryFlowServiceImpl implements CategoryFlowService {

    private CategoryService categoryService;

    private ItemService itemService;

    /**
     * Constructor.
     * 
     * @param categoryService - service for category management.
     * @param itemService - service for item management.
     */
    public CategoryFlowServiceImpl(CategoryService categoryService, ItemService itemService) {
        this.categoryService = categoryService;
        this.itemService = itemService;
    }

    /**
     * {@inheritDoc}
     */
    public List<CategoryBean> getAllCategories() {
        List<CategoryBean> result = new ArrayList<CategoryBean>();
        List<Category> categories = categoryService.getAll();
        for (Category category : categories) {
            result.add(new CategoryBean(category, false));
        }
        return result;
    }

    /**
     * {@inheritDoc}
     */
    public CategoryBean getCategory(long id, boolean copyItems) {
        Category category = categoryService.get(id);
        CategoryBean result = new CategoryBean(category, copyItems);
        return result;
    }

    /**
     * {@inheritDoc}
     */
    public void deleteCategory(CategoryBean category) {
        categoryService.delete(category.getId());
    }

    /**
     * {@inheritDoc}
     */
    public void saveCategory(CategoryBean category) {
        if (category.getId() != null) {
            categoryService.update(category.getId(), category.getName(), category.getItemIds());
        } else {
            categoryService.create(category.getName(), category.getItemIds());
        }
    }

    /**
     * {@inheritDoc}
     */
    public List<ItemBean> getAvailableItems() {
        List<Item> items = itemService.getAllItemsWithNoCategoryAssigned();
        List<ItemBean> result = new ArrayList<ItemBean>();
        for (Item item : items) {
            result.add(new ItemBean(item.getId(), item.getName()));
        }
        return result;
    }
}
